package com.open.party.cloud.view.home.eJia

import android.os.Bundle
import android.view.Gravity
import android.view.View
import android.widget.AdapterView
import android.widget.ArrayAdapter
import android.widget.TextView
import androidx.appcompat.widget.AppCompatSpinner
import androidx.core.content.ContextCompat
import androidx.recyclerview.widget.GridLayoutManager
import cn.android.x.model.data.ResultInfo
import cn.sinothk.hussars.parent.ImageSelectBaseActivity
import com.jiangyy.easydialog.CommonDialog
import com.open.party.cloud.R
import com.open.party.cloud.ServerConfig
import com.open.party.cloud.model.*
import com.open.party.cloud.model.data.Api
import com.open.party.cloud.model.data.CodeValue
import com.open.party.cloud.view.freePhoto.adpater.ImageSelectedShowAdapter
import com.open.party.cloud.viewModel.PartyViewModel
import com.sinothk.android.utils.XUtils
import com.sinothk.dialog.bottomDialog.dateDialog.TimePickerDialog
import com.sinothk.dialog.bottomDialog.dateDialog.data.Type
import com.sinothk.image.selected.ImgSelectEntity
import com.sinothk.image.selector.PhotoPreviewActivity
import com.sinothk.image.selector.SelectModel
import com.sinothk.rxretrofit.RxRetrofit
import com.sinothk.rxretrofit.param.RetrofitParam
import com.sinothk.switchTabView.style1.UIUtil
import kotlinx.android.synthetic.main.party_life_add.*
import kotlinx.android.synthetic.main.party_life_add.levelSpinner
import kotlinx.android.synthetic.main.party_life_add.mRvAlbumSelected
import org.greenrobot.eventbus.Subscribe
import org.greenrobot.eventbus.ThreadMode
import rx.Subscriber
import rx.android.schedulers.AndroidSchedulers
import rx.schedulers.Schedulers
import java.io.File
import java.text.SimpleDateFormat
import java.util.*

open class PartyLifeAddActivity : ImageSelectBaseActivity(), View.OnClickListener {
    var viewModel: PartyViewModel? = null

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.party_life_add)

        setViewTitle("新增活动", "提交") { ddPartyLife() }

        viewModel = PartyViewModel()

        initLevelView()
        setListener()
        setImg()
    }

    private fun setListener() {
        startTimeItem.setOnClickListener(this)
        endTimeItem.setOnClickListener(this)
    }

    private fun ddPartyLife() {

        if (!XUtils.net().isConnected) {
            XUtils.toast().show(R.string.net_error)
            return
        }

        val titleStr: String = titleTv.text.toString()
        if (XUtils.string().isEmpty(titleStr)) {
            XUtils.toast().show("请输入活动主题")
            return
        }

        val leaderStr: String = leaderTv.text.toString()
        if (XUtils.string().isEmpty(leaderStr)) {
            XUtils.toast().show("请输入负责人姓名")
            return
        }

        val addressStr: String = addressTv.text.toString()
        if (XUtils.string().isEmpty(addressStr)) {
            XUtils.toast().show("请输入活动地址")
            return
        }

        val contentStr: String = contentTv.text.toString()
        if (XUtils.string().isEmpty(contentStr)) {
            XUtils.toast().show("请输入活动描述")
            return
        }

        if (startTime == null) {
            XUtils.toast().show("请选择活动开始时间")
            return
        }

        if (endTime == null) {
            XUtils.toast().show("请选择活动结束时间")
            return
        }

        if (typeBean == null) {
            XUtils.toast().show("请选择活动类型")
            return
        }

        val partyLifeVo = PartyLifeVo()
        partyLifeVo.name = titleStr
        partyLifeVo.dutyPerson = leaderStr
        partyLifeVo.addr = addressStr
        partyLifeVo.content = contentStr

        partyLifeVo.lifeType = typeBean
        partyLifeVo.startTime = XUtils.date().getDateStrByDate(startTime!!)
        partyLifeVo.endTime = XUtils.date().getDateStrByDate(endTime!!)

        // 处理图片
        if (imgSelectList.size > 0) {
            val fileInfoList = ArrayList<FileEntity>()
            for (imgBean in imgSelectList) {
                fileInfoList.add(FileEntity(imgBean.url, imgBean.bizId))
            }
            partyLifeVo.fileList = fileInfoList
        }

        showLoadingDialog("正在提交")
        viewModel!!.addPartyLife(partyLifeVo)
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public fun eventBusCallback(result: ResultInfo<PartyLifeBean>) {
        if (result.eventType != "addPartyLife") {
            return
        }

        hideLoadingDialog()

        when (result.code) {
            ResultInfo.SUCCESS -> {
                finish()
            }
            ResultInfo.TOKEN_OVERDUE -> {
            }
            else -> {
                XUtils.toast().show(result.msg)
            }
        }
    }

    override fun onClick(v: View?) {
        when (v) {
            startTimeItem -> {
                showDateSelected("startTime")
            }
            endTimeItem -> {
                showDateSelected("endTime")
            }
        }
    }

    // 时间
    var startTime: Date? = null
    var endTime: Date? = null

    private fun showDateSelected(flag: String) {
        val oneYear: Long = 365 * 24 * 60 * 60 * 1000L
        val mDialogYearMonth: TimePickerDialog = TimePickerDialog.Builder()
            .setTitleStringId("选择时间")
            .setType(Type.ALL)
            .setMinMillseconds(System.currentTimeMillis() - (70 * oneYear))
            .setMaxMillseconds(System.currentTimeMillis() + (5 * oneYear))
            .setThemeColor(ContextCompat.getColor(this, R.color.colorPrimary))
            .setCallBack { _, millSeconds ->

                val dateObj = Date(millSeconds)
                val selectedMonth: String = SimpleDateFormat("yyyy-MM-dd HH:mm", Locale.getDefault()).format(dateObj)

                if (flag == "startTime") {
                    if (endTime != null && dateObj.time > endTime!!.time) {
                        XUtils.toast().show("开始时间不能在结束时间之后")
                        return@setCallBack
                    }

                    startTimeTv.text = selectedMonth
                    startTime = dateObj
                } else if (flag == "endTime") {

                    if (startTime != null && dateObj.time < startTime!!.time) {
                        XUtils.toast().show("结束时间不能在开始时间之前")
                        return@setCallBack
                    }

                    endTimeTv.text = selectedMonth
                    endTime = dateObj
                }
            }
            .build()

        mDialogYearMonth.show(supportFragmentManager, "year_month")
    }

    // 活动类型
    var typeBean: DictionaryBean? = null
    private fun initLevelView() {
        val typeBeanList = ArrayList<DictionaryBean>()
        //    DZBDH("党员大会"),
        //    ZBWYH("支委会"),
        //    DXZH("党小组会"),
        //    DK("党课"),
        //    DRHD("主题党日活动"),
        //    DZZHJ("党组织换届"),
        typeBeanList.add(DictionaryBean("DZBDH", "党员大会"))
        typeBeanList.add(DictionaryBean("ZBWYH", "支委会"))
        typeBeanList.add(DictionaryBean("DXZH", "党小组会"))

        typeBeanList.add(DictionaryBean("DK", "党课"))
        typeBeanList.add(DictionaryBean("DRHD", "主题党日活动"))
        typeBeanList.add(DictionaryBean("DZZHJ", "党组织换届"))

        val typeValueList = ArrayList<String>()
        for (typeBean in typeBeanList) {
            typeValueList.add(typeBean.desc)
        }

        initSpinnerView(levelSpinner, typeValueList, object : AdapterView.OnItemSelectedListener {
            override fun onNothingSelected(parent: AdapterView<*>?) {
            }

            override fun onItemSelected(parent: AdapterView<*>?, view: View?, position: Int, id: Long) {

                if (view != null) {
                    val tv = view as TextView
                    tv.setTextColor(ContextCompat.getColor(this@PartyLifeAddActivity, R.color.page_content))
                    tv.paint.textSize = UIUtil.sp2px(this@PartyLifeAddActivity, 14f).toFloat()
                    tv.gravity = Gravity.START
                    typeBean = typeBeanList[position]
                }
            }
        })
    }

    private var spinnerAdapter: ArrayAdapter<String>? = null

    private fun initSpinnerView(
        spinner: AppCompatSpinner, streetStrList: ArrayList<String>, itemSelectedListener: AdapterView.OnItemSelectedListener?
    ) {
        spinnerAdapter = ArrayAdapter(this, R.layout.street_spinner_item, streetStrList!!)
        spinnerAdapter!!.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        spinner.adapter = spinnerAdapter
        spinner.dropDownVerticalOffset = 100

        spinner.onItemSelectedListener = itemSelectedListener
    }

    // ============================= 图片部分
    var bizId = ""
    var bizType = BizType.PARTY_LIFE_IMG_ADD

    private var mAlbumSelectedShowAdapter: ImageSelectedShowAdapter? = null
    var imgSelectList: ArrayList<ImgSelectEntity> = ArrayList()
    private fun setImg() {
        mAlbumSelectedShowAdapter = ImageSelectedShowAdapter(this, 8)
        mRvAlbumSelected.layoutManager = GridLayoutManager(this, 4)
        mRvAlbumSelected.setHasFixedSize(true)
        mRvAlbumSelected.adapter = mAlbumSelectedShowAdapter

        mAlbumSelectedShowAdapter!!.setOnItemClickListener { _, position ->
            if (imgSelectList.size == position) {
//                openSysCamera(BizType.FREE_PHOTO_DEAL_WITH_IMG)
                gotoSelectImg(this@PartyLifeAddActivity, CodeValue.IMG_SELECT_CODE, SelectModel.SINGLE, true)
            } else {
                //图片展示界面
                val imgList: ArrayList<String> = ArrayList()
                for (imgEntity: ImgSelectEntity in imgSelectList) {
                    imgList.add(imgEntity.filePath)
                }
                PhotoPreviewActivity.start(this@PartyLifeAddActivity, position, imgList)
            }
        }

        mAlbumSelectedShowAdapter!!.setItemDelClick { position ->
            dialog(position)
        }
    }

    /*
     * Dialog对话框提示用户删除操作
     * position为删除图片位置
     */
    private fun dialog(position: Int) {
        CommonDialog.Builder(this)
            .setTitle("提示")
            .setMessage("确认移除已添加的图片吗？")
            .setPositiveButton("确认") {
                if (mAlbumSelectedShowAdapter!!.itemCount > 0) {
                    delPosition = position
                    // 删除服务器文件
                    delFileById(imgSelectList[position].id)
                }
            }.setNegativeButton("取消") {

            }.show()
    }

    private var delPosition: Int = 0

    override fun upLoad(filePath: String, fileName: String) {
        // 传单文件文件和键值对
        RxRetrofit.init(ServerConfig.SERVER_URL, ServerConfig.getHeader()).create(Api::class.java)
            .uploadFile(bizId, bizType, "", RetrofitParam.createFileParam("file", File(filePath)))
            .subscribeOn(Schedulers.io())
            .observeOn(AndroidSchedulers.mainThread())
            .subscribe(object : Subscriber<ResultInfo<FileEntity>>() {

                override fun onStart() {
                    super.onStart()
                }

                override fun onNext(result: ResultInfo<FileEntity>?) {
                    if (result != null) {
                        if (result.code == 0) {
                            if (result.data != null) {

                                this@PartyLifeAddActivity.bizId = result.data.bizId

                                val imgSelectEntity: ImgSelectEntity? = ImgSelectEntity()
                                imgSelectEntity!!.id = result.data.id.toString()
                                imgSelectEntity.filePath = filePath
                                imgSelectEntity.url = result.data.url
                                imgSelectEntity.bizId = fileName

                                imgSelectList.add(imgSelectEntity)

                                mAlbumSelectedShowAdapter?.setData(imgSelectList)
                                return
                            } else {
                                XUtils.toast().show("无文件信息")
                            }
                        } else {
                            XUtils.toast().show(result.msg)
                        }
                    } else {
                        XUtils.toast().show("提交失败")
                    }
                }

                override fun onCompleted() {
                }

                override fun onError(e: Throwable?) {
                    if (e != null) {
                        XUtils.toast().show("文件上传失败")
                    }
                }
            })
    }

    private fun delFileById(id: String) {

        val ids: Array<String> = arrayOf(id)

        // 传单文件文件和键值对
        RxRetrofit.init(ServerConfig.SERVER_URL, ServerConfig.getHeader()).create(Api::class.java)
            .delFileById(ids)
            .subscribeOn(Schedulers.io())
            .observeOn(AndroidSchedulers.mainThread())
            .subscribe(object : Subscriber<ResultInfo<Boolean>>() {

                override fun onStart() {
                    super.onStart()
                    showLoadingDialog("正在删除")
                }

                override fun onNext(result: ResultInfo<Boolean>?) {

                    hideLoadingDialog()

                    if (result != null) {
                        if (result.code == 0) {
                            if (result.data != null && result.data) {

                                // 移除展示数据
                                imgSelectList.removeAt(delPosition)
                                // 刷新界面
                                mAlbumSelectedShowAdapter?.setData(imgSelectList)
                                mAlbumSelectedShowAdapter?.notifyDataSetChanged()
                                return
                            } else {
                                XUtils.toast().show(result.msg)
                            }
                        } else {
                            XUtils.toast().show(result.msg)
                        }
                    } else {
                        XUtils.toast().show("删除失败")
                    }
                }

                override fun onCompleted() {
                }

                override fun onError(e: Throwable?) {
                    hideLoadingDialog()
                    if (e != null) {
                        XUtils.toast().show("文件删除失败")
                    }
                }
            })
    }

    // ============================================================================
}